package com.rp.common.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

/**
 * 动态Bean
 * @author HuangJian
 *
 */
public class DynamicBean {
	
	/**
	 * 实体Object
	 */
	private Object object = null;

	/**
	 * 属性map
	 */
	private BeanMap beanMap = null;

	public DynamicBean() {
		super();
	}
	
	public DynamicBean(Map<String, Object> propertyMap) {
		this.object = generateBean(propertyMap);
		this.beanMap = BeanMap.create(this.object);
	}

	/**
	 * 给bean属性赋值
	 * @param property  属性名
	 * @param value 属性值
	 */
	public void setValue(String property, Object value) {
		beanMap.put(property, value);
	}

	/**
	 * 通过属性名得到属性值
	 * @param property 属性名
	 * @return 属性值
	 */
	public Object getValue(String property) {
		return beanMap.get(property);
	}

	/**
	 * 得到该实体bean对象
	 * @return
	 */
	public Object getObject() {
		return this.object;
	}

	/**
	 * @param propertyMap
	 * @return
	 */
	private Object generateBean(Map<String, Object> propertyMap) {
		BeanGenerator generator = new BeanGenerator();
		Set<String> keySet = propertyMap.keySet();
		for (Iterator<String> i = keySet.iterator(); i.hasNext();) {
			String key = (String) i.next();
			generator.addProperty(key, (Class<?>) propertyMap.get(key));
		}
		return generator.create();
	}
	
	/**
	 * 示例
	 * @param args
	 */
	public static void main(String[] args) {

		// 设置类成员属性
		HashMap<String, Object> propertyMap = new HashMap<String, Object>();

		try {
			propertyMap.put("id", Class.forName("java.lang.Integer"));
			propertyMap.put("name", Class.forName("java.lang.String"));
			propertyMap.put("open", Class.forName("java.lang.Boolean"));

			// 生成动态 Bean
			DynamicBean bean = new DynamicBean(propertyMap);

			// 给 Bean 设置值
			bean.setValue("id", 1);
			bean.setValue("name", "广西电网");
			bean.setValue("open", true);
			
			//System.out.println(bean.getValue("open"));
			
	        
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
}
